package com.tzxs.pay.main.gather;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.Html;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.FragmentDepositBinding;
import com.tzxs.pay.main.baiduvoice.BaiduSpeechClient;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.base.OnMultiClickListener;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.AutTradedDetailActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.gather.model.BankBean;
import com.tzxs.pay.main.gather.model.ScanAutBean;
import com.tzxs.pay.main.gather.viewmodel.BankViewModel;
import com.tzxs.pay.main.onlineaut.AmountFilter;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.ClickUtil;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.ScanActivity;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.SystemUtil;
import com.tzxs.pay.util.ViewDialog;
import com.tzxs.pay.util.viewmodel.Callback;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 押金收款
 */
public class DepositActivity extends BaseActivity<FragmentDepositBinding> {
    /****测试前置摄像头扫码预授权，发布时注释****/
//    private ScannedResultBroadcastReceiver scannedResultBroadcastReceiver = new ScannedResultBroadcastReceiver() {
//        @Override
//        protected void handleScannedResult(Bundle bundle) {
//            scanAutResult(bundle);
//        }
//    };
    /****************************************/
    private OnMultiClickListener onMultiClickListener = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            Intent intent;
            switch (v.getId()) {
                //扫描二维码
                case R.id.sweep:
                    requestScanPermission(SCAN_CODE);
                    break;
                case R.id.authorization_list:
                    intent = new Intent(DepositActivity.this, AutListActivity.class);
                    startActivity(intent);
                    break;
                case R.id.authorization_list_search:
                    intent = new Intent(DepositActivity.this, SearchAutActivity.class);
                    startActivity(intent);
                    break;
                case R.id.sweep_aut:
                    //扫码预授权
                    if (TextUtils.isEmpty(dataBinding.depositMoneyCount.getText().toString())) {
                        Snackbar.make(v, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(dataBinding.depositNote.getText().toString())) {
                        Snackbar.make(v, "请输入备注信息!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    requestScanPermission(SCAN_AUT_CODE);
                    /****测试前置摄像头扫码预授权，发布时注释****/
//                    try {
//                        AidlUtil.getInstance().scanDecoder();
//                    } catch (RemoteException ex) {
//                        Log.e(TAG, "ex: " + ex);
//                    }
                    /****************************************/
                    break;

                case R.id.bank_card_aut:
                    //银行卡预授权收款
                    if (TextUtils.isEmpty(dataBinding.depositMoneyCount.getText().toString())) {
                        Snackbar.make(dataBinding.depositNoteLay, "请输入收款金额!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(dataBinding.depositNote.getText().toString())) {
                        Snackbar.make(dataBinding.depositNoteLay, "请输入备注信息!", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    //防止快速点击
                    if (!ClickUtil.isFasClick()) {

                        bankViewModel.createBankOrder(Double.parseDouble(dataBinding.depositMoneyCount.getText().toString()),
                                "auth", dataBinding.depositNote.getText().toString(),
                                0, "0", () -> {
                                    Log.d(TAG, "onClick: 创建普通收款订单成功：");
                                    startGather();
                                });
                    }
                    break;
                //使用说明
                case R.id.deposit_use_tip:
                    Intent useinfo = new Intent(DepositActivity.this, UserInfoActivity.class);
                    startActivity(useinfo);
                    break;
            }
        }
    };
    private static final String TAG = DepositActivity.class.getSimpleName();
    private static final int SCAN_CODE = 100;//扫码requestCode
    private static final int SCAN_AUT_CODE = 101;//扫码预授权
    private static final int BANK_AUT_CODE = 103;//银行卡预授权
    private BillViewModel model;
    private RxPermissions permissions;//权限申请
    private ProgressDialog dialog;
    private Intent bankIntent;
    private BankViewModel bankViewModel;

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_deposit;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.orange));  //设置押金收款界面状态栏颜色
        /****测试前置摄像头扫码预授权，发布时注释****/
//        registerReceiver(scannedResultBroadcastReceiver, new IntentFilter("com.shengpaysdk.qrcode.scan"));
        /****************************************/
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        dataBinding.authorizationListSearch.setOnClickListener(onMultiClickListener);
        dataBinding.depositToolbar.setTitle("");
        dataBinding.depositToolbar.setNavigationOnClickListener(v -> {
            closeKeyBoard();
            onBackPressed();
        });
        dataBinding.authorizationList.setOnClickListener(onMultiClickListener);
        dataBinding.sweepAut.setOnClickListener(onMultiClickListener);
        permissions = new RxPermissions(this);
        dataBinding.bankCardAut.setOnClickListener(onMultiClickListener);
        dataBinding.depositUseTip.setOnClickListener(onMultiClickListener);
        dataBinding.depositMoneyCount.setFilters(new InputFilter[]{new AmountFilter()});
        showKeyBoard(dataBinding.depositMoneyCount);
        initIntent();
        dataBinding.sweep.setOnClickListener(onMultiClickListener);
        if (SystemUtil.getSystemModel().contains("P1") || SystemUtil.getSystemModel().contains("A8")) {
            dataBinding.bankCardAut.setVisibility(View.VISIBLE);
        } else {
            dataBinding.bankCardAut.setVisibility(View.GONE);
        }
        //监听snackbarText的变化
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                if (s.contains("等待用户支付超时") || s.contains("未授权成功")) {
                    showDepositDely(s);
                } else {
                    Toast.makeText(DepositActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            }
        });
        model.dialogText.observe(this, s -> {
            if (s == null) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            } else {
                dialog = ProgressDialog.show(this, "正在交易...", s, false);
            }
        });
        bankViewModel.snackText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s != null) {
                    if (s.contains("等待用户支付超时") || s.contains("未授权成功")) {
                        showDepositDely(s);
                    } else {
                        Toast.makeText(DepositActivity.this, s, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    /****测试前置摄像头扫码预授权，发布时注释****/
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        unregisterReceiver(scannedResultBroadcastReceiver);
//    }

    /****************************************/
    //显示支付超时dialog
    private void showDepositDely(String content) {
        ViewDialog dialog = new ViewDialog();
        dialog.setLayoutId(R.layout.deposit_dialog);
        dialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.accept_dialog_title);
            TextView ok = view.findViewById(R.id.ok);
            if (content.contains("等待用户支付超时")) {
                String result = String.valueOf(Html.fromHtml(content));
                int start = result.indexOf("(");
                int end = result.indexOf(")");
                SpannableStringBuilder spannableString = new SpannableStringBuilder(result);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FE4655")),
                        start + 1, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                title.setText(spannableString);
            } else if (content.contains("未授权成功")) {
                title.setText(content);
            }
            ok.setOnClickListener(v -> dialog.dismiss());
        });
        dialog.show(getSupportFragmentManager(), "0");
    }

    //获取到打印的图标类型
    private int getBitmapType(String type) {
        int result = -1;
        switch (type) {
            case "0":
                result = 0;
                break;

            case "1":
                result = 1;
                break;

            case "2":
                result = 2;
                break;
        }
        return result;
    }

    //显示键盘
    private void showKeyBoard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Objects.requireNonNull(imm).showSoftInput(editText, 0);
                editText.setSelection(editText.getText().length());
            }
        }, 200);
    }

    //关闭软键盘
    private void closeKeyBoard() {

        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getWindow().peekDecorView();
        if (Objects.requireNonNull(manager).isActive(dataBinding.depositMoneyCount)) {
            manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

    }

    //显示打印dialog
    private void showPrintDialog(ScanAutBean.DataBean bean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("授权成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            //print.setOnClickListener(v -> print(bean));
            print.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View view) {
                    print(bean);
                }
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
                //跳转到收款详情
                String tradeNum = bean.getOut_order_no();
                Intent intent = new Intent(this, AutTncActivity.class);
                intent.putExtra("orderId", tradeNum);
                intent.putExtra("autType", "nor");
                intent.putExtra("needPrint", false);
                startActivity(intent);
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    //关闭软键盘
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeKeyBoard();
        }
        return super.onKeyDown(keyCode, event);
    }

    //开始银行卡预授权 调用sdk
    private void startGather() {
        if (bankViewModel.bankBean != null) {
            //获取订单成功后
            BankBean.DataBean bean = bankViewModel.bankBean.get();
            if (bean != null) {
                String str = bean.getAmount();
                double du = Double.valueOf(str) * 100;
                int result = (int) du;
                Log.d(TAG, "getInfo: 最后金额结果:" + result);
                bankIntent.putExtra("barcodeType", "0");//指定为银行卡消费
                bankIntent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                bankIntent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                bankIntent.putExtra("transName", "3");//交易类型  消费 退款   0是消费
                bankIntent.putExtra("remark", "暂时备注123");
                //用户联备注
                bankIntent.putExtra("printMerchantInfo",
                        "交易订单号:" + bean.getOut_trade_no() + "        "
                                + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("printMerchantInfo2", bean.getOut_trade_no());
                bankIntent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                        + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("priInfo2", bean.getOut_trade_no());
                //判断是否安装盛付通支付
                if (isInstallShengfuPay()) {
                    startActivityForResult(bankIntent, BANK_AUT_CODE);
                } else {
                    Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //判断是否安装盛付通支付sdk
    private boolean isInstallShengfuPay() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            if (SystemUtil.getSystemModel().equals("P1") || SystemUtil.getSystemModel().equals("P1_4G") || SystemUtil.getSystemModel().contains("A8")) {
                if (list.get(i).packageName.equalsIgnoreCase("sunmi.fw2.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("sunmimi.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("com.shengpay.smartpos.shengpaysdk")) {

                    return true;
                }
            }
            Log.d(TAG, "isInstallShengfuPay: 包名：" + list.get(i).packageName);
        }
        return false;
    }

    //抽取各个交易类型公共的字段
    private Intent initIntent() {
        bankIntent = new Intent();
        bankIntent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        bankIntent.putExtra("appId", this.getPackageName());
        return bankIntent;
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        if (TextUtils.isEmpty(amount)) return null;
        while (amount.length() < 12) {
            amount = "0" + amount;
        }
        return amount;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SCAN_CODE && data != null) {//扫码订单查询
            Bundle bundle = data.getExtras();
            dealWithQrCode(bundle);
        }
        if (requestCode == SCAN_AUT_CODE && data != null) {//扫码预授权
            Bundle bundle = data.getExtras();
            scanAutResult(bundle);
        }
        if (requestCode == BANK_AUT_CODE && data != null) {//银行卡交易结果返回处理
            Bundle extras1 = data.getExtras();
            //此处传入resultCode
            bankAutPay(resultCode, extras1, data);
        }
    }

    /**
     * 处理二维码扫描结果,订单查询
     *
     * @param bundle
     */
    private void dealWithQrCode(Bundle bundle) {
        if (bundle == null) return;
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            if (result == null) {
                return;
            }
            boolean strHead = result.contains("fu");
            Log.d(TAG, "onActivityResult: 小票抬头是fu开头：" + strHead + "结果:" + result);
            if (result.startsWith("fu")) {//当时预授权订单时
                model.getAutBillDetail(result, new Callback() {
                    @Override
                    public void success() {
                        if (model.autDeatil.get().getUnfreeze_status() == 1) {//订单已被解冻
                            Intent intent = new Intent(DepositActivity.this, AutTradedDetailActivity.class);
                            intent.putExtra("orderId", result);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(DepositActivity.this, AutTncActivity.class);
                            intent.putExtra("orderId", result);
                            startActivity(intent);
                        }
                    }
                });
            } else {//否则是收款订单  或者分期订单  预授权结算后变成普通订单
                Intent intent = new Intent(this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", result);
                startActivity(intent);
            }
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 扫码预授权
     *
     * @param bundle
     */
    private void scanAutResult(Bundle bundle) {
        if (bundle == null) return;
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            if (result == null) {
                return;
            }
            //扫码完成后调起生成订单支付
            model.scanAutPay(dataBinding.depositNote.getText().toString(),
                    result, dataBinding.depositMoneyCount.getText().toString(), () -> {
                        dialog.dismiss();
                        //获取到返回的订单号信息
                        ScanAutBean.DataBean bean = model.scanAutPayBean.get();
                        String content = "扫码收款成功  ¥" + dataBinding.depositMoneyCount.getText().toString() + " " + getCurrentTime();

                        model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                        });
                        if (bean != null) {

                            print(bean);
                            BaiduSpeechClient.getInstance().speak("押金收款"+dataBinding.depositMoneyCount.getText().toString()+"元");
                            showPrintDialog(bean);
                        }
                    });
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

    //打印
    private void print(ScanAutBean.DataBean bean) {
        if (bean == null) {
            return;
        }
        List<String> printContent = Objects.requireNonNull(bean).getPrint_array();
        String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        aidlUtil.enterPrinterBuffer(true);
        //打印支付方式图标
        commenPrint(printContent, aidlUtil, bitmapType);
//        //打印支付方式图标
//        if (SystemUtil.getSystemModel().contains("A8")) {
//            aidlUtil.printBitmapForA8(bitmapType, 2);
//        } else {
//            int resId = getResId(bitmapType);
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
//            aidlUtil.printBitmap(bitmap, "2", "2", resId);
//        }
//        //抬头
//        aidlUtil.printText(printContent.get(1), "32", "32", "1",
//                true, false);
//        aidlUtil.printBlankLine("1", "10");
//        //门店
//        aidlUtil.printText(printContent.get(2), "24", "24", "1",
//                false, false);
//        //订单支付方式text开始
//        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
//                "24", "24", "0",
//                false, false);
//        //业务记录
//        aidlUtil.printText(printContent.get(4), "32", "32", "0",
//                true, false);
//        //业务记录内容
//        if (!TextUtils.isEmpty(printContent.get(5))){
//            aidlUtil.printText("\n" + printContent.get(5)
//                            .replace("\\n", "\n"), "24", "24", "0",
//                    false, false);
//        }
//
//
//        //退款 ||收款
//        aidlUtil.printText(printContent.get(6), "32", "32", "0",
//                true, false);
//        //退款获取收款内容
//        aidlUtil.printText("\n" + printContent.get(7)
//                        .replace("\\n", "\n"), "24", "24", "0",
//                false, false);
//        aidlUtil.printBlankLine("1", "10");
//        //打印二维码
//        aidlUtil.printQr(printContent.get(8), "8", "3");
//        //收银员 //打印时间
//        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//
//
//        aidlUtil.printBlankLine("1", "10");
//        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText("\n" + printContent.get(11).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(12),
//                "24", "24", "1", false, false);
//        aidlUtil.printBlankLine("5", "30");
//        aidlUtil.printCommit();
    }

    //处理银行卡收款相关
    private void bankAutPay(int resultCode, Bundle extras1, Intent data) {
        boolean success = false;
        if (extras1 == null) {
            return;
        }
        String payResult = null;//交易结果
        Set<String> keySet = extras1.keySet();
        switch (resultCode) {
            case Activity.RESULT_OK:
                Toast.makeText(this, "交易成功", Toast.LENGTH_SHORT).show();
                success = true;
                StringBuilder resultBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    resultBuilder.append(str);
                }
                Log.d(TAG, "onActivityResult: 支付结果：" + resultBuilder.toString());
                payResult = resultBuilder.toString();
                String content = "银行卡预授权成功收款  ¥" + dataBinding.depositMoneyCount.getText().toString() + " " + getCurrentTime();
                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                    BaiduSpeechClient.getInstance().speak("押金收款"+dataBinding.depositMoneyCount.getText().toString()+"元");
                });
                break;
            case Activity.RESULT_CANCELED:
                String reason = data.getStringExtra("reason");
                Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
                success = false;
                StringBuilder failBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    failBuilder.append(str);
                }
                payResult = failBuilder.toString();
                break;
        }
        Log.d(TAG, "onActivityResult:payResult :银行卡预授权交易信息======" + payResult);
        //上传交易结果

        //回调上传交易结果
        boolean finalSuccess = success;
        bankViewModel.uploadTradeInfo(payResult, () -> {
            if (finalSuccess) {
                Intent intent = new Intent(this, AutTncActivity.class);
                intent.putExtra("orderId", bankViewModel.bankBean.get().getOut_trade_no());
                intent.putExtra("autType", "bank");
                intent.putExtra("needPrint", true);
                startActivity(intent);
            }
            Log.d(TAG, "bankPay: 上传交易信息成功!");
        });
    }

    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");
        return simpleDateFormat.format(new Date());
    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission(int code) {
        permissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {
            if (permission.granted) {
                scanCode(code);
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(DepositActivity.this, "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).show();
            } else {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
    }

    //开始扫描二维码
    private void scanCode(int code) {
        Intent scanIntent = new Intent(this, ScanActivity.class);

        startActivityForResult(scanIntent, code);
    }
}
